import { useState, useEffect } from "react";
import "./organization.css"
import {
  Skeleton, Input, Table, Space, Tag, Button, Badge,
  Modal, Form, Select, Card,
  Switch,
  Tooltip, message
} from "antd";
import {
  PlusOutlined, UserOutlined,
  EditOutlined, SaveOutlined,
  UsergroupDeleteOutlined,
} from '@ant-design/icons';
import { AddDuty } from "../../component/organization/AddDuty";
import { DutyDetails } from "../../component/organization/DutyDetails";
import { Delete_Post, Get_AllPost } from "../../service/organization";

const { Search } = Input;

export const Duty = () => {
  // 状态管理
  const [isShow, setIsShow] = useState(true);
  const [searchValue, setSearchValue] = useState('');
  const [loading, setLoading] = useState(false);

  // 模态框状态
  const [detailVisible, setDetailVisible] = useState(false);
  const [addVisible, setAddVisible] = useState(false);
  const [currentDuty, setCurrentDuty] = useState(null);
  
  // 分页参数管理
  const [pagination, setPagination] = useState({
    current: 1,        // 当前页码
    pageSize: 5,      // 每页条数
    total: 0,          // 总数据条数
  });

  // 岗位数据
  const [post, setPost] = useState([]);
  
  // 表单实例
  const [dutyForm] = Form.useForm();

  // 中医理疗馆岗位表格列定义
  const columns = [
    {
      title: '岗位名称',
      dataIndex: 'name',
      key: 'name',
      width: "200px",
      render: (text, record) => (
        <Space>
          <UserOutlined />
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: '岗位等级',
      dataIndex: 'lv',
      key: 'lv',
      width: "150px",
      render: (level) => {
        const levelMap = {
          '低级': 'default',
          '中级': 'processing',
          '高级': 'success',
        };
        return <Badge status={levelMap[level]} text={level} />;
      },
    },
    {
      title: '岗位职责',
      dataIndex: 'responsibility',
      key: 'responsibility',
      width: '200px',
      render: (responsibilities) => {
        // 确保responsibilities是数组
        const responsibilityList = Array.isArray(responsibilities) ? responsibilities : [];
        return (
          <div>
            {responsibilityList.slice(0, 2).map((item, index) => (
              <Tooltip key={index} title={item}>
                <Tag
                  color="default"
                  style={{
                    marginBottom: 4,
                    marginRight: 4,
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    maxWidth: '200px'
                  }}
                >
                  {item}
                </Tag>
              </Tooltip>
            ))}
            {responsibilityList.length > 2 && (
              <Tag color="default">+{responsibilityList.length - 2}项</Tag>
            )}
          </div>
        );
      },
    },
    {
      title: '岗位人数',
      dataIndex: 'count',
      key: 'count',
      width: "100px",
      render: (text, record) => (
        <Space>
          <UsergroupDeleteOutlined />
          <span>{text || 0}</span>
        </Space>
      ),
    },
    {
      title: '使用状态',
      dataIndex: 'isBan',
      key: 'isBan',
      render: (isBan, record) => (
        <Switch
          size="small"
          checkedChildren="启用"
          unCheckedChildren="禁用"
          checked={!isBan} // 根据实际接口含义调整
          onChange={(checked) => handleStatusChange(record.id, checked)}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            size="small"
            type="primary"
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button
            size="small"
            danger
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 获取岗位数据
  const bind_post = async (page = pagination.current, pageSize = pagination.pageSize, search = searchValue) => {
    setLoading(true);
    try {
      const res = await Get_AllPost({ 
        page: page, 
        limit: pageSize,
        key: search // 添加搜索参数
      });
      
      if (res.code === 0) {
        setPost(res.data.data || []);
        setPagination(prev => ({
          ...prev,
          current: page,
          pageSize: pageSize,
          total: res.data.total || 0
        }));
      } else {
        message.error('获取岗位数据失败: ' + (res.msg || '未知错误'));
        setPost([]);
        setPagination(prev => ({ ...prev, total: 0 }));
      }
    } catch (error) {
      console.error('获取岗位数据出错:', error);
      message.error('获取岗位数据时发生错误');
      setPost([]);
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    bind_post();
    
    // 骨架屏定时器
    const timer = setTimeout(() => {
      setIsShow(false);
    }, 2000);

    return () => clearTimeout(timer);
  }, []);

  // 搜索处理
  const onSearch = (value) => {
    setSearchValue(value);
    // 搜索时重置到第一页
    setPagination(prev => ({ ...prev, current: 1 }));
    bind_post(1, pagination.pageSize, value);
  };

  // 搜索输入变化处理（防抖）
  const handleSearchChange = (e) => {
    const value = e.target.value;
    setSearchValue(value);
    // 如果输入为空，立即搜索；否则可以添加防抖
    if (value === '') {
      bind_post(1, pagination.pageSize, '');
    }
  };

  // 分页变化处理
  const handleTableChange = (newPagination, filters, sorter) => {
    setPagination(newPagination);
    bind_post(newPagination.current, newPagination.pageSize, searchValue);
  };

  // 查看岗位详情
  const handleViewDetail = (record) => {
    setCurrentDuty(record);
    setDetailVisible(true);
  };

  // 删除岗位
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `您确定要删除 "${record.name}" 岗位吗？此操作不可撤销。`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
         
          const res = await Delete_Post({ id: record.id });
          if (res.code === 0) {
            message.success('删除成功');
            bind_post(); // 重新加载数据
          } else {
            message.error('删除失败: ' + (res.msg || '未知错误'));
          }
        } catch (error) {
          console.error('删除岗位出错:', error);
          message.error('删除岗位时发生错误');
        }
      }
    });
  };

  // 状态切换
  const handleStatusChange = async (id, checked) => {
    try {
      // const res = await ChangeIsBan_Post({ id: id, isBan: !checked }); // 根据实际接口调整
      // if (res.code === 0) {
      //   message.success('状态更新成功');
      //   bind_post(); // 重新加载数据
      // } else {
      //   message.error('状态更新失败: ' + (res.msg || '未知错误'));
      // }
    } catch (error) {
      console.error('更新状态出错:', error);
      message.error('更新状态时发生错误');
    }
  };

  // 打开新增岗位模态框
  const handleAddDuty = () => {
    dutyForm.resetFields();
    setAddVisible(true);
  };

  // 提交新增岗位表单
  const handleAddFormSubmit = () => {
    dutyForm.validateFields()
      .then(values => {
        // 这里应该调用新增岗位的API
        // 示例代码，需要根据实际接口调整
        console.log('新增岗位数据:', values);
        
        Modal.success({
          title: '操作成功',
          content: `岗位 ${values.name} 已成功创建`
        });
        
        setAddVisible(false);
        bind_post(); // 重新加载数据
      })
      .catch(info => {
        console.log('表单验证失败:', info);
      });
  };

  // 表格分页配置
  const tablePagination = {
    ...pagination,
   
    showTotal: (total, range) => 
      `共 ${total} 条数据`,
    pageSizeOptions: ['5', '10', '20', '50'],
  };

  return (
    <div className="dept-container">
      {isShow ? (
        <Skeleton paragraph={{ rows: 10 }} active />
      ) : (
        <div className="dept-main">
          <div className="dept-right">
            <div className="search-box">
              <div style={{ flex: 1, textAlign: "center" }}>
                <Search
                  placeholder="请输入岗位名称或职责"
                  allowClear
                  onSearch={onSearch}
                  value={searchValue}
                  onChange={handleSearchChange}
                  style={{ width: 400 }}
                />
              </div>
              <div>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={handleAddDuty}
                >
                  新增岗位
                </Button>
              </div>
            </div>

            <div style={{ marginTop: 10 }}>
              <Table
                bordered
                columns={columns}
                dataSource={post}
                pagination={tablePagination}
                loading={loading}
                onChange={handleTableChange}
                rowKey="id"
                locale={{ emptyText: "暂无岗位数据" }}
              />
            </div>
          </div>
        </div>
      )}

      {/* 岗位详情模态框 */}
      <Modal
        title={<span>岗位详情</span>}
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        width={900}
        style={{ top: "50px" }}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)}>
            关闭
          </Button>,
        
        ]}
        destroyOnHidden
      >
        {currentDuty && (
          <DutyDetails data={currentDuty} />
        )}
      </Modal>

      {/* 新增岗位模态框 */}
      <Modal
        title={<span><PlusOutlined /> 新增岗位</span>}
        open={addVisible}
        onCancel={() => setAddVisible(false)}
        width={700}
        style={{ top: "50px" }}
        footer={[
        
        ]}
        destroyOnHidden
      >
        <AddDuty  onCancel={() => {
          setAddVisible(false);
          bind_post();
        }} />
      </Modal>
    </div>
  );
};